$(()=>{
  let $width = $('#width'),
      $height = $('#height'),
      $btnCal = $('#calc'),
      $perimeter = $('#perimeter'),
      $area = $('#area'),
      $widthValidate = $('#width-validate'),
      $heightValidate = $('#height-validate'),
      isPassValidate = false;
      $btnCal.click(()=>{
        if(!isPassValidate) return;
        let w = Number($width.val()),
            h = Number($height.val());
        let p = (w+h)*2,
            a = w*h;
        $perimeter.val(p);
        $area.val(a);
      })
      $width.focusout(() =>{
        let result = validate($width,$widthValidate);
        isPassValidate = result.isOK;
        if(!result.isOK){
          $widthValidate.html(result.reason);
          $width.select();
        }else{
          $widthValidate.html('');
        }
      })
      $width.keypress($width=>{
        isKey($width.key,$width.target.value,$width.target.selectionStart)||$width.preventDefault()
      }
      )
      $height.focusout(()=>{
        let result = validate($height,$heightValidate);
        isPassValidate = result.isOK;
        if(!result.isOK){
          $heightValidate.html(result.reason);
          $height.select();
        }else{
          $heightValidate.html('');
        }
      })
      $height.keypress($height=>{
        isKey($height.key,$height.target.value,$height.target.selectionStart)||$height.preventDefault()
      })
})

function validate(input,output){
  let result = {
    isOK:false,
    reason:''
  }
  if(input.val()===''){
    result.reason = '该字段不能为空';
    return result;
  }
  let val = Number(input.val());
  if(isNaN(val)){
    result.reason = '该字段应该为数值';
    return result;
  }
  if(val < 0){
    result.reason = '该数值不能小于零';
    return result;
  }
  result.isOK = true;
  return result;
}
function isKey(key,content,pos){
  //非法字符
  if(/[abcdf-zABCDF-Z`~!@#$%^&*()=+[\]{}|;:'",<>/?\\]/.test(key)){
    return false;
  }
  //小数点
  if(key==='.'){
    if(pos===0) return false;
    if(content.indexOf('.')!==-1) return false;
    if(pos>0 && /[-eE]/.test(content.slice(0,pos))) return false;
  }
  //e和E
  if(key==='e' || key==='E'){
    if(pos===0) return false;
    if(content.indexOf('e') !==-1 ||content.indexOf('E')!==-1) return false;
    if(content.slice(pos,content.length).indexOf('.') !==-1) return false;
    if(pos>0&&/[-.]/.test(content.slice(pos-1,pos))) return false;
  }
  //负号
  if(key==='-'){
    if(pos===0) return false;
    if(pos>0&&/[0-9.]/.test(content.slice(pos-1,pos))) return false;
    if(pos>0&&content.indexOf('-')!==-1) return false;
  }
  return true;
}
